#include "Channel.h"
#include <cassert>
#include <iostream>

#include "Impl.h"
#include "Client.h"
#include "Buffer.h"

namespace frame {
Channel::Channel(IChannelHandlerAdapter::Ptr handlerAdapter)
: handlerAdapter(handlerAdapter)
, id(0)
, opened(false)
, connected(false)
{
    std::cout << "Channel:constructor" << std::endl;
}
Channel::~Channel() {
    std::cout << "Channel:destructor" << std::endl;
}
int Channel::open(){
    if(!opened){
        assert(impl != nullptr);
        int ret = impl->open();
        opened = true;
        return ret;
    }
    return 0;
}
void Channel::close(){
    if(opened){
        assert(impl != nullptr);
        impl->close(); //TODO: check ret value
        opened = false;
    }
}


int Channel::write(const char * buf, int size) {
    if(isConnected()){
        assert(impl != nullptr);
        return impl->write(std::make_shared<WriteBuffer>(buf, size));
    }
    return -1;
}
int Channel::write(const std::string & str){
    if(isConnected()){
        assert(impl != nullptr);
        return impl->write(std::make_shared<WriteBuffer>(str));
    }
    return -1;
}
int Channel::disconnect() {
    if(isConnected()){
        assert(impl != nullptr);
        int ret = impl->disconnect();
        connected = false;

        this->close();
        return ret;
    }
    return 0;
}

const std::string & Channel::getRemoteIp() {
    return remoteIp;
}
const int Channel::getRemotePort() {
    return remotePort;
}
const std::string & Channel::getLocalIp() {
    return localIp;
}
const int Channel::getLocalPort() {
    return localPort;
}

void Channel::setConnected(bool connected){
    this->connected = connected;
}

} //end of namespace frame
